package com.jwd.avmanager.parse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jwd.avmanager.server.JedisClient;
import com.jwd.avmanager.util.DebugLogger;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;



public class RequestParserTask {

    Logger logger = LoggerFactory.getLogger(RequestParserTask.class.getName());

    private final FullHttpRequest request;
    private final ChannelHandlerContext ctx;

    public RequestParserTask(ChannelHandlerContext ctx, FullHttpRequest request) {
        this.request = request;
        this.ctx = ctx;
    }


    public void startDeal() {
        //解析请求
        int i = request.refCnt();
        System.out.println(i);
        if (request.method().equals(HttpMethod.POST)) {
            //解析uri
            doPost();

        } else {
            //返回错误码，目前仅支持post请求
            DebugLogger.err(logger,"RequestParserTask request.method() is unsupported");
            sendErrorResponse(HttpResponseStatus.METHOD_NOT_ALLOWED);
        }
    }

    /**
     * 处理post请求
     *
     * @return 是否只有对应的uri
     */
    public void doPost() {
        String uri = request.uri();
        //判断头部请求是否是json
        String contentType = request.headers().get("Content-Type");
        if (!"application/json".equals(contentType)) {
            sendErrorResponse(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
            return;
        }
        ByteBuf content = request.content();
        System.out.println("可读数据:"+content.readableBytes());
        byte[] bytes = new byte[content.readableBytes()];
        content.getBytes(0,bytes);
        String  paramJson= new String(bytes, StandardCharsets.UTF_8);
//        String paramJson = content.getCharSequence(0, content.readableBytes(), StandardCharsets.UTF_8).toString();

        if (paramJson.isEmpty()) {
            sendErrorResponse(HttpResponseStatus.BAD_REQUEST);
            return;
        }
        //校验token
        String token = request.headers().get("token");
        String redisId = JedisClient.getInstance().get(token);//从redis的token获取管理员id
        if (redisId == null) {
            DebugLogger.err(logger,"token is null");
            sendErrorResponse(HttpResponseStatus.UNAUTHORIZED);
        }
        if ("/pullStream".equals(uri)) {
            //解析
            try {
                JSONObject jsonObject = JSON.parseObject(paramJson);
                String devId = jsonObject.getString("devId");//获取设备id
                if (devId == null || devId.isEmpty()) {
                    //打印错误日志
                    DebugLogger.err(logger, "param err: devId is null");
                    sendErrorResponse(HttpResponseStatus.BAD_REQUEST);
                    return;
                }

                //开始执行任务
                pullStream(devId);
            } catch (Exception e) {
                //打印错误日志
                DebugLogger.err(logger,"param err :"+e.getMessage());
                sendErrorResponse(HttpResponseStatus.BAD_REQUEST);
            }

        } else {
            DebugLogger.err(logger,"uri is unsupported:"+uri);
            sendErrorResponse(HttpResponseStatus.NOT_FOUND);
        }

    }

    /**
     * 处理拉流逻辑
     */
    private void pullStream(String devId) {
        //TODO 1.操作缓存，通过tcp发送拉流指令给设备
        //TODO 2.操作完成以后，通过http返回流地址信息
        String body = "{\"type\":\"content\",\"payload\":\"今天天气怎么样\"}";//模拟请求完成
        sendJsonResponse(body);
    }


    /**
     * 处理响应码200的时候，按照这个发送
     *
     * @param json
     */
    private void sendJsonResponse(String json) {
        ByteBuf byteBuf = Unpooled.copiedBuffer(json, StandardCharsets.UTF_8);
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);

        boolean keepAliveDefault = HttpVersion.HTTP_1_1.isKeepAliveDefault();
        if (keepAliveDefault) {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");

        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
        ctx.writeAndFlush(response);
        ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        if (!keepAliveDefault) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    /**
     * 非200响应码按照这个发送
     *
     * @param responseCode
     */
    private void sendErrorResponse(HttpResponseStatus responseCode) {

        DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseCode);
        ctx.writeAndFlush(httpResponse);
        ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        future.addListener(ChannelFutureListener.CLOSE);
    }
}
